# -*- coding: UTF-8 -*-
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QMessageBox, QDialog, QVBoxLayout, QFormLayout, QComboBox, QLineEdit, QHBoxLayout, \
    QPushButton, QDialogButtonBox
import sqlite3
import jwt


def edit_device(parent, row, devices):
    # 首先检查管理员权限
    is_admin = False
    main_window = parent
    while main_window and not hasattr(main_window, 'settings'):
        main_window = main_window.parent()
    
    if main_window and hasattr(main_window, 'settings'):
        token = main_window.settings.value('user_token')
        if token:
            try:
                user_info = jwt.decode(token, 'your-secret-key', algorithms=['HS256'])
                is_admin = user_info.get('role') == '管理员'
            except jwt.ExpiredSignatureError:
                pass
    
    if not is_admin:
        QMessageBox.warning(parent, "权限不足", "只有管理员可以编辑设备信息,请点击右上角的个人中心登录")
        return

    device = devices[row]
    dialog = QDialog(parent)
    dialog.setWindowTitle("编辑设备")
    layout = QVBoxLayout(dialog)
    
    # 创建表单布局
    form_layout = QFormLayout()
    
    # 创建输入字段
    fields = {}
    for field, label in [
        ("vendor", "厂商"),
        ("device_type", "设备类型"),
        ("model", "型号"),
        ("host", "主机名"),
        ("ip", "IP地址"),
        ("remote_type", "远程类型"),
        ("protocol", "协议"),
        ("port", "端口"),
        ("username", "用户名"),
        ("password", "密码"),
        ("enable_password", "Enable密码")
    ]:
        line_edit = QLineEdit()
        value = device.get(field, "")
        line_edit.setText(str(value))
        
        # 密码字段特殊处理
        if field in ["password", "enable_password"]:
            line_edit.setEchoMode(QLineEdit.Password)
        
        fields[field] = line_edit
        form_layout.addRow(label, line_edit)
    
    layout.addLayout(form_layout)
    
    # 添加按钮
    button_box = QDialogButtonBox(
        QDialogButtonBox.Ok | QDialogButtonBox.Cancel
    )
    button_box.accepted.connect(dialog.accept)
    button_box.rejected.connect(dialog.reject)
    layout.addWidget(button_box)
    
    if dialog.exec() == QDialog.Accepted:
        # 更新数据
        update_data = {field: widget.text() for field, widget in fields.items()}
        
        # 更新数据库
        try:
            with sqlite3.connect('device_config/config_file/device_info.db') as conn:
                cursor = conn.cursor()
                
                set_clause = ", ".join([f"{k} = ?" for k in update_data.keys()])
                values = list(update_data.values())
                values.append(device['ip'])  # WHERE 子句的值
                
                sql = f"UPDATE deviceinfo SET {set_clause} WHERE ip = ?"
                cursor.execute(sql, values)
                conn.commit()
                
                QMessageBox.information(dialog, "成功", "设备信息已更新")
                
                # 刷新设备列表
                parent.load_devices()
                
        except sqlite3.Error as e:
            QMessageBox.critical(dialog, "错误", f"更新失败: {str(e)}")
